package com.ctshk.rpc.cms.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.MD5Util;
import com.ctshk.rpc.cms.dto.ContentDTO;
import com.ctshk.rpc.cms.dto.LinkTypeDTO;
import com.ctshk.rpc.cms.dto.PushDTO;
import com.ctshk.rpc.cms.entity.LinkType;
import com.ctshk.rpc.cms.entity.Push;
import com.ctshk.rpc.cms.mapper.LinkTypeMapper;
import com.ctshk.rpc.cms.mapper.PushMapper;
import com.ctshk.rpc.cms.req.PushAddReq;
import com.ctshk.rpc.cms.req.PushQueryReq;
import com.ctshk.rpc.cms.req.PushUpdateReq;
import com.ctshk.rpc.cms.service.IPushService;
import com.ctshk.rpc.goods.dto.CMSCommodityDTO;
import com.ctshk.rpc.goods.service.ICMSCommodityService;
import com.ctshk.rpc.localfun.dto.LocalFunResourceDTO;
import com.ctshk.rpc.localfun.req.LocalFunResourceReq;
import com.ctshk.rpc.localfun.service.ILocalFunResourceService;
import com.ctshk.rpc.scenic.dto.ScenicProductListDTO;
import com.ctshk.rpc.scenic.req.ScenicProductListReq;
import com.ctshk.rpc.scenic.service.IScenicProductService;
import com.ctshk.rpc.season.dto.FixedSeasonProductPageDTO;
import com.ctshk.rpc.season.service.ISeasonFixedProductService;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.service.ISysUserService;
import com.ctshk.rpc.tour.dto.schedule.SeriesTripScheduleBasicDTO;
import com.ctshk.rpc.tour.service.ISeriesTripScheduleService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 推送管理 服务实现类
 * </p>
 *
 * @author LiZhiming
 * @since 2021-04-23
 */
@DubboService
public class PushServiceImpl extends ServiceImpl<PushMapper, Push> implements IPushService {

    @Autowired
    private LinkTypeMapper linkTypeMapper;

    @Autowired
    private ContentServiceImpl contentService;

    @DubboReference
    private ISysUserService sysUserService;

    @DubboReference
    private ISeasonFixedProductService seasonFixedProductService;

    @DubboReference
    private ILocalFunResourceService localFunResourceService;

    @DubboReference
    private ICMSCommodityService icmsCommodityService;

    @DubboReference
    private IScenicProductService scenicProductService;

    @DubboReference
    private ISeriesTripScheduleService seriesTripScheduleService;

    private static final String APP_KEY = "6087dcb8f00c2e19b93d0d4b";
    private static final String APP_MASTER_SECRET = "cjv7wqwzuzosc916hpretlntpt6ji6e4";

    public static void main(String[] arges) {
        System.out.println(System.currentTimeMillis());
        String method = "POST";
        String url = "http://msg.umeng.com/api/send";
        String json = "{\n" +
                "  \"appkey\": \"6087dcb8f00c2e19b93d0d4b\",\n" +
                "  \"timestamp\": 1622708063918,\n" +
                "  \"device_tokens\": \"Ar9MAgyPzhVz1NPNR1P2f3mYKetVmd6zK_bi800eljD5\",\n" +
                "  \"type\": \"unicast\",\n" +
                "  \"payload\": {\n" +
                "    \"display_type\": \"notification\",\n" +
                "    \"body\": {\n" +
                "      \"ticker\": \"Hello World\",\n" +
                "      \"title\": \"你好\",\n" +
                "      \"text\": \"来自友盟推送\",\n" +
                "      \"after_open\": \"go_app\"\n" +
                "    }\n" +
                "  }\n" +
                "}";
        String ams = "cjv7wqwzuzosc916hpretlntpt6ji6e4";
        String s = JSON.toJSONString(json);
        String s1 = MD5Util.stringMd5(method + url + s + ams);
        System.out.println(s1);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result insert(PushAddReq req, TokenUser tu) {
        Push push = EntityUtil.copy(req, Push.class);
        LocalDateTime now = LocalDateTime.now();
        Long id = IdWorker.getId();
        push.setCreateId(tu.getId());
        push.setGmtCreate(now);
        push.setId(id);
        push.setIsDeleted(IsDeletedCode.NO.getCode());
        int insert = baseMapper.insert(push);
        //新增成功banner后再新增链接类型
        if (insert > 0) {
            LinkType copy = EntityUtil.copy(req.getLinkTypeReq(), LinkType.class);
            copy.setCorrelationId(id);
            copy.setCreateId(tu.getId());
            copy.setGmtCreate(now);
            copy.setIsDeleted(IsDeletedCode.NO.getCode());
            linkTypeMapper.insert(copy);
            //TODO 需要在这里看看立即发送怎么处理逻辑(1立即推送2定时推送)
            if (push.getPushTimeType() == 1) {
                //TODO 1云平台2.其它。。。
                if (push.getPushChannel() == 1) {

                }
            }
            return Result.success(id);
        }
        return Result.failed(SystemError.CMS_23000);
    }

    @Override
    public Result<PushDTO> queryById(String pushId) {
        PushDTO b = null;
        QueryWrapper<Push> qw = new QueryWrapper<>();
        qw.lambda().eq(Push::getIsDeleted, IsDeletedCode.NO.getCode())
                .eq(Push::getId, pushId);
        Push push = baseMapper.selectOne(qw);
        if (push != null) {
            b = EntityUtil.copy(push, PushDTO.class);
            QueryWrapper<LinkType> qwlt = new QueryWrapper<>();
            qwlt.lambda().eq(LinkType::getIsDeleted, IsDeletedCode.NO.getCode())
                    .eq(LinkType::getCorrelationId, pushId);
            LinkTypeDTO lt = EntityUtil.copy(linkTypeMapper.selectOne(qwlt), LinkTypeDTO.class);
            b.setLinkTypeDTO(lt);
            //調用接口填充產品信息
            setProduct(lt);
        }
        return Result.success(b);
    }

    @Override
    public PageResponse<PushDTO> queryList(PushQueryReq req) {
        Page<Push> page = new Page(req.getPageNo(), req.getPageSize());
        QueryWrapper<Push> qw = new QueryWrapper();
        qw.lambda().eq(Push::getIsDeleted, IsDeletedCode.NO.getCode())
                .eq(req.getPushChannel() != null, Push::getPushChannel, req.getPushChannel())
                .eq(req.getPushTitle() != null, Push::getPushTitle, req.getPushTitle())
                .eq(req.getPushTypeId() != null, Push::getPushTypeId, req.getPushTypeId())
                .eq(req.getPushTypeName() != null, Push::getPushTypeName, req.getPushTypeName());
        Page<Push> PushPage = baseMapper.selectPage(page, qw);
        if (CollectionUtils.isNotEmpty(PushPage.getRecords())) {
            List<PushDTO> pushDTOS = EntityUtil.copyList(PushPage.getRecords(), PushDTO.class);
            for (PushDTO pushDTO : pushDTOS) {
                UserDTO userDTO = sysUserService.loadUserInfo(pushDTO.getCreateId(), 1);
                if (userDTO != null) {
                    pushDTO.setUserName(userDTO.getCnSurname() + userDTO.getCnName());
                }
                QueryWrapper<LinkType> qwlt = new QueryWrapper<>();
                qwlt.lambda().eq(LinkType::getIsDeleted, IsDeletedCode.NO.getCode())
                        .eq(LinkType::getCorrelationId, pushDTO.getId());
                LinkType linkType = linkTypeMapper.selectOne(qwlt);
                LinkTypeDTO lt = EntityUtil.copy(linkType, LinkTypeDTO.class);
                pushDTO.setLinkTypeDTO(lt);
                //調用接口填充產品信息
                setProduct(lt);
            }
            return new PageResponse<>(pushDTOS,
                    page.getCurrent() == 1, page.getTotal() <= (page.getCurrent() *
                    page.getSize()), page.getTotal(), page.getCurrent(), page.getSize());
        }
        return new PageResponse<>(null,
                page.getCurrent() == 1, page.getTotal() <= (page.getCurrent() *
                page.getSize()), page.getTotal(), page.getCurrent(), page.getSize());
    }

    private void setProduct(LinkTypeDTO lt) {
        //調用接口填充產品信息
        if (lt.getProductId() != null) {
            List<Long> ids = new ArrayList<>();
            ids.add(lt.getProductId());
            switch (lt.getLinkType()) {
                case 3://文檔
                    Result<ContentDTO> contentDTOResult = contentService.queryById(lt.getProductId().toString());
                    if (contentDTOResult.getData() != null) {
                        lt.setProduct(contentDTOResult.getData());
                    }
                    break;
                case 4://旅行团
                    SeriesTripScheduleBasicDTO stsb = seriesTripScheduleService.findScheduleBasic(lt.getProductId());
                    lt.setProduct(stsb);
                    break;
                case 5://套票
                    List<FixedSeasonProductPageDTO> seasonProductList = seasonFixedProductService.getSeasonProductList(lt.getProductId().toString());
                    if (seasonProductList != null && seasonProductList.size() > 0) {
                        lt.setProduct(seasonProductList.get(0));
                    }
                    break;
                case 6://酒店
                    break;
                case 7://门票
                    ScenicProductListReq splr = new ScenicProductListReq();
                    splr.setIds(ids);
                    List<ScenicProductListDTO> data = scenicProductService.getListByIds(splr).getData();
                    if (data != null && data.size() > 0) {
                        lt.setProduct(data.get(0));
                    }
                    break;
                case 8://当地玩乐
                    LocalFunResourceReq lfrr = new LocalFunResourceReq();
                    lfrr.setProductIds(ids);
                    List<LocalFunResourceDTO> localFunResourceDTOS = localFunResourceService.queryListByProductIds2(lfrr);
                    if (localFunResourceDTOS != null && localFunResourceDTOS.size() > 0) {
                        lt.setProduct(localFunResourceDTOS.get(0));
                    }
                    break;
                case 9://商品
                    List<CMSCommodityDTO> cmsCommodityDTOS = icmsCommodityService.selectCMSCommodityDTOByIds(ids);
                    if (cmsCommodityDTOS != null && cmsCommodityDTOS.size() > 0) {
                        lt.setProduct(cmsCommodityDTOS.get(0));
                    }
                    break;
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result update(PushUpdateReq req, TokenUser tu) {
        LocalDateTime now = LocalDateTime.now();
        Push copy = EntityUtil.copy(req, Push.class);
        copy.setModifiedId(tu.getId());
        copy.setGmtModified(now);
        int i = baseMapper.updateById(copy);
        if (i > 0) {
            LinkType copy1 = EntityUtil.copy(req.getLinkTypeDTO(), LinkType.class);
            copy1.setModifiedId(tu.getId());
            copy1.setGmtModified(now);
            QueryWrapper<LinkType> qw = new QueryWrapper<>();
            qw.lambda().eq(LinkType::getCorrelationId, req.getId())
                    .eq(LinkType::getIsDeleted, IsDeletedCode.NO.getCode());
            linkTypeMapper.update(copy1, qw);
            return Result.success(req.getId());
        }
        return Result.failed(SystemError.CMS_23002);
    }

}
